package com.example.cart.database;

import androidx.room.Database;
import androidx.room.RoomDatabase;
import androidx.room.Transaction;

import com.example.cart.dao.CartDao;
import com.example.cart.dao.ProductDao;
import com.example.cart.entity.Cart;
import com.example.cart.entity.Product;

import java.util.List;

@Database(entities = {Product.class, Cart.class}, version = 1, exportSchema = true)
public abstract class ShoppingDatabase extends RoomDatabase {

    public abstract ProductDao productDao();

    public abstract CartDao cartDao();

    @Transaction
    public void initProducts(List<Product> productList) {
        ProductDao productDao = productDao();
        for (Product product : productList) {
            productDao.insert(product);
        }
    }

    @Transaction
    public void addProductToCart(Product product) {
        CartDao cartDao = cartDao();
        // 查询商品在购物车中是否存在
        Cart existedCart = cartDao.selectByProductId(String.valueOf(product.getId()));
        if (existedCart == null) {
            Cart cart = new Cart();
            cart.setProductId(String.valueOf(product.getId()));
            cart.setQuantity(1);
            cart.setAmount(product.getPrice());
            cartDao.insert(cart);
        } else {
            existedCart.setQuantity(existedCart.getQuantity() + 1);
            existedCart.setAmount(existedCart.getAmount() + product.getPrice());
            cartDao.update(existedCart);
        }
    }
}
